package me.lxw.blogsystem.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import me.lxw.blogsystem.domain.User;
import me.lxw.blogsystem.utils.DBUtils;

/**
 * 用户数据访问对象
 * 
 * @author 梁兴威
 *
 */
public class UserDAO {
	public User findById(int id) throws SQLException {
		// 1.获取链接
		Connection conn = DBUtils.getConnection();

		// 2.拼接SQL
		String sql = "select * from user where id=?";
		// 3.获取执行者，发送SQL
		PreparedStatement st = conn.prepareStatement(sql);
		st.setInt(1, id);
		ResultSet rs = st.executeQuery();
		// 4.处理结果
		User user = null;
		while (rs.next()) {
			user = new User();
			user.setId(rs.getInt("id"));
			user.setUsername(rs.getString("username"));
			user.setPassword(rs.getString("password"));
			user.setNickname(rs.getString("nickname"));
			user.setDescription(rs.getString("description"));
			user.setAvatarImg(rs.getString("avatar_img"));
		}

		// 5.关闭资源
		DBUtils.closeResource(conn, st, rs);

		return user;
	}

	public User findByUsernameAndPassword(String username, String password) throws SQLException {
		// 1.获取链接
		Connection conn = DBUtils.getConnection();

		// 2.拼接SQL
		String sql = "select * from user where username=? and password=?";
		// 3.获取执行者，发送SQL
		PreparedStatement st = conn.prepareStatement(sql);
		st.setString(1, username);
		st.setString(2, password);
		ResultSet rs = st.executeQuery();
		// 4.处理结果
		User user = null;
		while (rs.next()) {
			user = new User();
			user.setId(rs.getInt("id"));
			user.setUsername(rs.getString("username"));
			user.setPassword(rs.getString("password"));
			user.setNickname(rs.getString("nickname"));
			user.setDescription(rs.getString("description"));
			user.setAvatarImg(rs.getString("avatar_img"));
		}

		// 5.关闭资源
		DBUtils.closeResource(conn, st, rs);

		return user;
	}
}
